<template>
  <div class="chapter-detail">
    <!-- 返回箭头按钮 -->
    <button class="back-btn" @click="goBack">← 返回</button>

    <!-- 加载中提示 -->
    <div v-if="loading">加载中...</div>

    <!-- 章节内容 -->
    <div v-else>
      <h2>{{ chapter.title }}</h2>
      <div
        class="chapter-content"
        @mouseup="handleSelection"
        @contextmenu="handleContextMenu"
      >
        <div
          v-for="(paragraph, index) in chapter.content"
          :key="index"
          class="paragraph"
          :data-paragraph-index="index"
        >
          <pre>{{ paragraph }}</pre>
          <!-- 显示注解按钮 -->
          <img
            v-if="getAnnotationsForParagraph(index).length"
            :src="annotationIcon"
            class="annotation-icon"
            @click="showParagraphAnnotations(index)"
          />
        </div>
      </div>
    </div>

    <teleport to="body">
      <transition name="modal-fade">
        <div v-if="showAnnotationDialog" class="modal-mask">
          <div class="annotation-modal">
            <div class="modal-header">
              <h3>段落注解</h3>
              <button class="close-btn" @click="showAnnotationDialog = false">
                &times;
              </button>
            </div>
            <div class="modal-scroll-body">
              <div
                v-for="anno in currentAnnotations"
                :key="anno.annotationId"
                class="annotation-item"
              >
                <span
                  class="type-tag"
                  :style="getTypeStyle(anno.annotationType)"
                >
                  {{ getTypeLabel(anno.annotationType) }}
                </span>
                <div class="quote-text">{{ anno.paragraphContent }}</div>
                <div class="annotation-content">
                  {{ anno.annotationContent }}
                </div>
                <!-- 内容保持原有结构 -->
              </div>
            </div>
          </div>
        </div>
      </transition>
    </teleport>

    <div
      v-if="showContextMenu"
      class="context-menu"
      :style="{ left: menuPosition.x + 'px', top: menuPosition.y + 'px' }"
    >
      <button @click="openAnnotationDialog">添加注解</button>
      <button @click="sendSelectedTextToAi">AI分析</button>
    </div>
    <teleport to="body">
      <transition name="modal-fade">
        <div v-if="dialogVisible" class="modal-mask">
          <div class="add-annotation-modal">
            <div class="modal-header">
              <h3>添加注解</h3>
              <button class="close-btn" @click="dialogVisible = false">
                &times;
              </button>
            </div>
            <div class="modal-body">
              <el-form>
                <el-form-item label="选中内容">
                  <el-input
                    type="textarea"
                    :value="paragraphContent"
                    :autosize="{ minRows: 3 }"
                    readonly
                  />
                </el-form-item>
                <el-form-item label="注解内容">
                  <el-input
                    v-model="annotationContent"
                    type="textarea"
                    :autosize="{ minRows: 4 }"
                  />
                </el-form-item>
                <el-form-item label="注解类型">
                  <el-select v-model="annotationType">
                    <el-option :value="1" label="普通笔记" />
                    <el-option :value="2" label="段落分析" />
                    <el-option :value="3" label="资源推荐" />
                    <el-option :value="4" label="情节探讨" />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div class="modal-footer">
              <button class="btn secondary" @click="dialogVisible = false">
                取消
              </button>
              <button class="btn primary" @click="saveAnnotation">保存</button>
            </div>
          </div>
        </div>
      </transition>
    </teleport>

    <!-- 上一章 和 下一章按钮 -->
    <div class="chapter-nav">
      <button class="prev-chapter" @click="goToPrevChapter" :disabled="loading">
        上一章
      </button>
      <button class="next-chapter" @click="goToNextChapter" :disabled="loading">
        下一章
      </button>
    </div>
    <img
      src="@/assets/imgs/assistant.png"
      class="ai-assistant-icon"
      @click="showAiDialog = true"
      draggable="false"
    />
    <teleport to="body">
      <transition name="modal-fade">
        <div v-if="showAiDialog" class="modal-mask">
          <AiAssistant
            v-if="showAiDialog"
            :visible="showAiDialog"
            :selectedContent="selectedContent"
            :chapter-id="chapterId"
            @close="showAiDialog = false"
            @clear-selected-content="clearSelectedContent"
            @save-annotation="handleAiAnnotation"
          />
        </div>
      </transition>
      <teleport to="body">
        <transition name="fade">
          <div v-if="showSelectionGuide" class="selection-guide-top">
            <div class="guide-text">请选择要关联的文本片段</div>
            <button class="guide-cancel" @click="cancelAnnotation">
              取消操作
            </button>
          </div>
        </transition>
      </teleport>
    </teleport>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  getChapterContent,
  getTotalChapters,
  saveAnnotationData,
  getAnnotations,
  updateLastReadChapter,
} from '@/apis/book' // 导入获取章节内容和总章节数的 API
import { ElMessage } from 'element-plus' // 引入 ElMessage 提示组件
import { useAccountStore } from '@/stores/useAccountStore'
import annotationIcon from '@/assets/imgs/annotation.png'
import AiAssistant from './AiAssistant.vue'
const accountStore = useAccountStore()

const route = useRoute()
const router = useRouter()

const chapter = ref({
  title: '',
  content: '',
  orderIndex: 1, // 新增
})
const loading = ref(true)

const chapterId = ref(Number(route.params.chapterId))
const totalChapters = ref(0) // 用来存储总章节数

// 获取章节内容的函数
const fetchChapterContent = async (contentUrl) => {
  try {
    const res = await fetch(contentUrl)
    const text = await res.text()
    // 使用正则分割段落（兼容不同换行格式）
    return text
      .split(/(?:<br\s*\/?>[\s\n]*){2,}/gi)
      .filter((p) => p.trim().length > 0)
      .map((p) => p.replace(/<br\s*\/?>/gi, '\n')) // 保留单换行符
  } catch (error) {
    return ['加载章节内容失败']
  }
}

// 获取章节内容
const getChapterDetails = async (chapterId) => {
  loading.value = true
  try {
    const response = await getChapterContent(chapterId)
    chapter.value = {
      title: response.data.title,
      content: await fetchChapterContent(response.data.contentUrl),
      orderIndex: response.data.orderIndex,
    }
    // ⬇️ 更新书架最近阅读章节
    await updateLastReadChapter(route.params.bookId, chapterId)
  } catch (error) {
    console.error('Failed to fetch chapter details:', error)
  } finally {
    loading.value = false
  }
}

// 获取总章节数
const getTotalChaptersCount = async () => {
  try {
    const response = await getTotalChapters(route.params.bookId) // 获取书籍的总章节数
    totalChapters.value = response.data
  } catch (error) {
    console.error('Failed to fetch total chapters:', error)
  }
}

// 监听路由变化
watch(
  () => route.params.chapterId,
  (newChapterId) => {
    chapterId.value = Number(newChapterId)
    getChapterDetails(chapterId.value) // 重新加载章节内容
  }
)

// 新增响应式数据
const selectedRange = ref(null)
const selectedParagraphIndex = ref(-1)
const showContextMenu = ref(false)
const menuPosition = ref({ x: 0, y: 0 })
const dialogVisible = ref(false)
const annotationContent = ref('')
const annotationType = ref(1)
const paragraphContent = ref('')

const openAnnotationDialog = () => {
  dialogVisible.value = true
  paragraphContent.value = selectedRange.value.toString().trim()
  showContextMenu.value = false
}

const handleContextMenu = (event) => {
  event.preventDefault()
  showContextMenu.value = true
  menuPosition.value = {
    x: event.clientX,
    y: event.clientY,
  }
}

// 处理文本选择
const handleSelection = () => {
  const selection = window.getSelection()
  if (!selection.rangeCount) return

  const range = selection.getRangeAt(0)
  const paragraphElement =
    range.startContainer.parentElement.closest('.paragraph')

  if (paragraphElement) {
    selectedParagraphIndex.value = parseInt(
      paragraphElement.dataset.paragraphIndex,
      10
    )
    selectedRange.value = range
    paragraphContent.value = selection.toString().trim()

    if (pendingAnnotation.value) {
      // 如果有 AI 帮你保存的注解，自动填充到注解内容里
      annotationContent.value = pendingAnnotation.value.text || ''
      annotationType.value = 1 // 可以默认选个类型，比如普通笔记
      pendingAnnotation.value = null
      showSelectionGuide.value = false // 隐藏顶部提示
      openAnnotationDialog() // 直接弹出注解窗口
    } else {
      showContextMenu.value = true
      menuPosition.value = {
        x: range.getBoundingClientRect().right,
        y: range.getBoundingClientRect().top,
      }
    }
  }
}

const showAnnotationDialog = ref(false)
const annotations = ref([])
const fetchAnnotations = async () => {
  try {
    const res = await getAnnotations({
      userId: accountStore.uid,
      bookId: route.params.bookId,
      chapterId: chapterId.value,
    })
    annotations.value = res.data || []
  } catch (err) {
    console.error('获取注解失败:', err)
  }
}

const currentAnnotations = ref([])

// 按段落索引分组注解
const annotationsByParagraph = computed(() => {
  return annotations.value.reduce((acc, anno) => {
    const index = anno.paragraphIndex
    if (!acc[index]) acc[index] = []
    acc[index].push(anno)
    return acc
  }, {})
})

// 获取指定段落的注解
const getAnnotationsForParagraph = (index) => {
  return annotationsByParagraph.value[index] || []
}

// 显示指定段落的注解
const showParagraphAnnotations = (index) => {
  currentAnnotations.value = getAnnotationsForParagraph(index)
  showAnnotationDialog.value = true
}
const typeStyles = {
  1: { background: '#67c23a' }, // 普通笔记
  2: { background: '#e6a23c' }, // 段落分析
  3: { background: '#f56c6c' }, // 资源推荐
  4: { background: '#909399' }, // 情节探讨
}

const typeLabels = {
  1: '笔记',
  2: '分析',
  3: '资源',
  4: '探讨',
}
// 注解类型映射
const getTypeStyle = (type) => {
  return typeStyles[type] || {}
}

const getTypeLabel = (type) => {
  return typeLabels[type] || '其他'
}

const saveAnnotation = async () => {
  if (!selectedRange.value) return

  try {
    const response = await saveAnnotationData({
      userId: accountStore.uid,
      bookId: route.params.bookId,
      chapterId: chapterId.value,
      paragraphIndex: selectedParagraphIndex.value,
      paragraphContent: paragraphContent.value,
      annotationContent: annotationContent.value,
      annotationType: annotationType.value,
      aiGenerated: false,
    })

    if (response.code === '200') {
      ElMessage.success('注解保存成功')
      dialogVisible.value = false
      await fetchAnnotations()
    } else {
      ElMessage.error('保存失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('保存失败：网络错误')
    console.error(error)
  }
}

// 打开对话框

// 初始化加载章节和总章节数
onMounted(() => {
  getChapterDetails(chapterId.value)
  getTotalChaptersCount() // 获取总章节数
  document.addEventListener('click', () => (showContextMenu.value = false))
  fetchAnnotations()
})

// 返回上一页
const goBack = () => {
  router.push({
    path: `/home/reading/book/${route.params.bookId}`,
  })
}

// 上一章
const goToPrevChapter = () => {
  if (chapter.value.orderIndex <= 1) {
    ElMessage.warning('已经是第一章了！')
  } else {
    router.push(`/book/${route.params.bookId}/chapter/${chapterId.value - 1}`)
  }
}

// 下一章
const goToNextChapter = () => {
  if (chapter.value.orderIndex >= totalChapters.value) {
    ElMessage.warning('已经是最后一章了！')
  } else {
    router.push(`/book/${route.params.bookId}/chapter/${chapterId.value + 1}`)
  }
}

const showAiDialog = ref(false)
const selectedContent = ref('') // 用来存储选中的文本

const sendSelectedTextToAi = () => {
  // 获取选中文本
  const selection = window.getSelection().toString().trim()
  selectedContent.value = selection // ✅ 传递选中文本
  showAiDialog.value = true
  showContextMenu.value = false
}

const clearSelectedContent = () => {
  selectedContent.value = ''
}

const showSelectionGuide = ref(false)
const pendingAnnotation = ref(null)

// 处理AI消息保存
const handleAiAnnotation = (message) => {
  pendingAnnotation.value = message
  showSelectionGuide.value = true
  showAiDialog.value = false
}
const cancelAnnotation = () => {
  pendingAnnotation.value = null // 把待处理的 AI 注解清空
  showSelectionGuide.value = false // 把提示也关掉
}
</script>

<style scoped>
.chapter-detail {
  padding: 20px;
  background-color: #faf0d7; /* 淡黄色，类似书页的颜色 */
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 为页面添加柔和的阴影 */
  max-width: 1000px; /* 限制最大宽度 */
  margin: 0 auto; /* 水平居中 */
}

h2 {
  font-size: 24px;
  margin-bottom: 20px;
  font-family: 'Georgia', serif; /* 给标题添加书籍常见的字体 */
}

.chapter-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #333;
  font-size: 16px;
  font-family: 'Times New Roman', serif;
  user-select: text; /* 允许文本被选中 */
}

.chapter-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: 'Times New Roman', serif;
  font-size: 16px;
}

.chapter-nav {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 20px;
  justify-content: center;
  z-index: 1000;
}

.prev-chapter,
.next-chapter {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}

.prev-chapter:disabled,
.next-chapter:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.back-btn {
  background: none;
  border: none;
  color: #007bff;
  font-size: 16px;
  cursor: pointer;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #ddd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 9999;
}

.context-menu button {
  display: block;
  padding: 8px 16px;
  width: 100%;
  text-align: left;
  background: none;
  border: none;
  cursor: pointer;
}

.context-menu button:hover {
  background: #f5f5f5;
}

.annotation-icon {
  position: absolute;
  right: 5px;
  bottom: 20px;
  cursor: pointer;
  width: 20px;
  height: 20px;
  opacity: 0.8;
  transition: opacity 0.2s;
}

.annotation-icon:hover {
  opacity: 1;
}

.paragraph {
  position: relative;
  padding-right: 30px;
  margin: 1em 0;
  border-radius: 4px;
  transition: background 0.3s;
  text-indent: 2em;
}

/* 合并注解对话框的样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: opacity 0.3s ease;
}

.annotation-modal,
.add-annotation-modal {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.2);
  width: 600px;
  max-width: 90vw;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  transform: translateY(-20px);
  transition: all 0.3s ease;
}

.modal-fade-enter-active .annotation-modal,
.modal-fade-enter-active .add-annotation-modal {
  transform: translateY(0);
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.25rem;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #666;
  cursor: pointer;
  padding: 0 8px;
}

.close-btn:hover {
  color: #333;
}

.modal-body,
.modal-scroll-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  padding: 8px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.secondary {
  background: #f0f0f0;
  color: #666;
  border: 1px solid #ddd;
}

.btn.secondary:hover {
  background: #e0e0e0;
}

.btn.primary {
  background: #409eff;
  color: white;
  border: 1px solid #409eff;
}

.btn.primary:hover {
  background: #337ecc;
}

/* 注解项样式 */
.annotation-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  border-left: 4px solid #409eff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.annotation-item:hover {
  transform: translateX(4px);
  transition: transform 0.2s ease;
}

.type-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8em;
  margin-bottom: 8px;
}

.quote-text {
  position: relative;
  padding-left: 12px;
  margin: 12px 0;
}

.quote-text::before {
  content: '“';
  position: absolute;
  left: -8px;
  top: -8px;
  color: #999;
  font-size: 1.4em;
}

.quote-text::after {
  content: '”'; /* 后引号 */
}

.ai-assistant-icon {
  position: fixed;
  top: 100px;
  right: 20px;
  width: 50px;
  height: 50px;
  z-index: 3000;
  cursor: pointer;
  transition: transform 0.2s;
}
.ai-assistant-icon:hover {
  transform: scale(1.1);
}

.selection-guide-top {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  backdrop-filter: blur(6px);
  color: #333;
  padding: 12px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
  z-index: 9999;
  display: flex;
  align-items: center;
  gap: 20px;
  font-size: 16px;
}

/* 引导文字 */
.selection-guide-top .guide-text {
  font-weight: 500;
}

/* 取消按钮 */
.selection-guide-top .guide-cancel {
  background: none;
  border: 1px solid #ccc;
  color: #666;
  padding: 6px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.selection-guide-top .guide-cancel:hover {
  background: #f5f5f5;
  border-color: #bbb;
}
</style>
